package com.cloudkinto.service.invoice.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cloudkinto.common.DicBusinessItemConstant;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.dao.CompanyDao;
import com.cloudkinto.entity.CompanyDo;
import com.cloudkinto.entity.InvoiceRecordDo;
import com.cloudkinto.entity.InvoiceTitleDo;
import com.cloudkinto.dao.InvoiceTitleDao;
import com.cloudkinto.extentity.InvoiceTitleOweDto;
import com.cloudkinto.service.invoice.InvoiceRecordService;
import com.cloudkinto.service.invoice.InvoiceTitleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;

import com.cloudkinto.service.invoice.vo.InvoiceTitleAddReq;
import com.cloudkinto.service.invoice.vo.InvoiceTitleDetailRes;
import com.cloudkinto.service.invoice.vo.InvoiceTitleOweDetailRes;
import com.cloudkinto.service.invoice.vo.InvoiceTitleUpdateReq;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author hjy
 * @since 2021-07-13
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class InvoiceTitleServiceImpl extends ServiceImpl<InvoiceTitleDao, InvoiceTitleDo> implements InvoiceTitleService {
    @Autowired
    private InvoiceTitleDao dao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private InvoiceRecordService invoiceRecordService;

    @Override
    public SingleResult addInit() {
        Map map = new HashMap();
        return SingleResult.success("");
    }

    @Override
    public InvoiceTitleAddReq add(InvoiceTitleAddReq req, Long userId, Long companyId) {
        if (companyId == null && req.getCompanyId() == null) {
            throw new BizException(SysConstant.Pls_Choose_Company);
        }
        InvoiceTitleDo entityDo = new InvoiceTitleDo();
        BeanUtils.copyProperties(req, entityDo);
        if (entityDo.getCompanyId() == null || entityDo.getCompanyId() == 0) {
            entityDo.setCompanyId(companyId);
        }
        handlerAddBefore(entityDo, userId);
        dao.insert(entityDo);
        return req;
    }

    //新增校验
    private void addCheck(Object req) {

    }

    @Override
    public List<InvoiceTitleOweDetailRes> oweList(Map<String, String> map) {
        String companyId = map.get("companyId");
        if (StringUtils.isBlank(companyId)) {
            throw new BizException(SysConstant.Error_Company);
        }
        String taxNumber = map.get("taxNumber");
        List<InvoiceTitleOweDto> invoiceTitleOweDtos = dao.selectOweList(map);

        List<InvoiceTitleOweDetailRes> list = new ArrayList<>();
        for (InvoiceTitleOweDto dto : invoiceTitleOweDtos) {
            InvoiceTitleOweDetailRes res = new InvoiceTitleOweDetailRes();
            BeanUtils.copyProperties(dto, res);
            if (dto.getInvoiceCount() > dto.getRechargeCount()) {
//                InvoiceRecordDo recordServiceOne = invoiceRecordService.getOne(new LambdaQueryWrapper<InvoiceRecordDo>()
//                        .eq(InvoiceRecordDo::getTaxNumber, dto.getTaxNumber())
//                        .ne(InvoiceRecordDo::getStatus, DicBusinessItemConstant.invoiceNotPassStatus)
//                        .orderByDesc(InvoiceRecordDo::getId)
//                        .last("limit 1"));
//                if (recordServiceOne != null && recordServiceOne.getInvoiceAmount() != null) {
//                    res.setOweAmount(recordServiceOne.getInvoiceAmount());
//                }
                int count = invoiceRecordService.getUnMatchInvoiceRecordCount(Long.parseLong(companyId), dto.getTaxNumber());
                if (StringUtils.isNotBlank(taxNumber) && taxNumber.equals(dto.getTaxNumber())) {
                    count -= 1;
                }
                res.setInvoicing(count <= 2);
                res.setOweAmount(count <= 2 ? 0 : 100);
            }
            else {
                res.setInvoicing(true);
            }
            list.add(res);
        }
        return list;
    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(InvoiceTitleDo entityDo, Long userId) {
        entityDo.setCreateBy(userId);
        entityDo.setCreateTime(new Date());
        entityDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
    }

    //将新增的do转换成要返回的实体
    private Object handlerAddAfter(InvoiceTitleDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public SingleResult updateInit(Long id) {
        return SingleResult.success(detail(id));
    }

    @Override
    public InvoiceTitleAddReq update(InvoiceTitleUpdateReq req, Long userId) {
        InvoiceTitleDo entityDo = dao.selectById(req.getId());
        if (entityDo == null) {
            throw new BizException(SysConstant.Error_Data_HadDelete);
        }
        BeanUtils.copyProperties(req, entityDo);
        handlerUpdateBefore(entityDo, userId);
        dao.updateById(entityDo);
        return req;
    }

    //编辑校验
    private void updateCheck(Object req) {

    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(InvoiceTitleDo entityDo, Long userId) {
        entityDo.setUpdateBy(userId);
        entityDo.setUpdateTime(new Date());
    }

    //做修改之后要执行的业务定制处理
    private Object handlerUpdateAfter(InvoiceTitleDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public int delete(Long id, Long userId) {
        InvoiceTitleDo entityDo = dao.selectById(id);
        handlerDeleteBefore(entityDo, userId);

        //判断这个抬头是否在使用中 固定月开
        CompanyDo companyDo = companyDao.selectOne(new LambdaQueryWrapper<CompanyDo>()
                .eq(CompanyDo::getLastInvoiceType, 0).eq(CompanyDo::getLastInvoiceTitleId, id).last(" order by id desc limit 1"));
        if (companyDo != null) {
            throw new BizException(SysConstant.InvoiceTitle_Delete_Error);
        }
        return dao.deleteById(id);
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(InvoiceTitleDo entityDo, Long userId) {
//        entityDo.setDeleteBy(userId);
//        entityDo.setDeleteTime(new Date());
    }

    @Override
    public InvoiceTitleDetailRes detail(Long id) {
        InvoiceTitleDo entityDo = dao.selectById(id);
        InvoiceTitleDetailRes res = new InvoiceTitleDetailRes();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    //查询明细之后要执行的业务定制处理
    private Object handlerDetailAfter(Object res) {
        return res;
    }

    @Override
    public SingleResult pageInit() {
        return SingleResult.success("");
    }

    @Override
    public List<InvoiceTitleDetailRes> getList(Map<String, String> map) {
        QueryWrapper<InvoiceTitleDo> wrapper = queryBuild(map);
        List<InvoiceTitleDo> list = dao.list(map);
        List<InvoiceTitleDetailRes> result = handlerListAfter(list);
        return result;
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
        IPage<InvoiceTitleDo> page = pageInit(map);
        List<InvoiceTitleDo> pageList = dao.listPage(page, map);
        List<InvoiceTitleDetailRes> resList = handlerListAfter(pageList);
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }

    //查询分页列表之后对列表数据的处理
    private List<InvoiceTitleDetailRes> handlerListAfter(List<InvoiceTitleDo> list) {
        List<InvoiceTitleDetailRes> result = new ArrayList<>();
        for (InvoiceTitleDo et : list) {
            InvoiceTitleDetailRes res = new InvoiceTitleDetailRes();
            BeanUtils.copyProperties(et, res);
            CompanyDo companyDo = companyDao.selectById(et.getCompanyId());
            if (companyDo != null) {
                res.setCompanyCode(companyDo.getCompanyCode());
            }
            result.add(res);
        }
        return result;
    }

    private IPage<InvoiceTitleDo> pageInit(Map<String, String> map) {
        IPage<InvoiceTitleDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<InvoiceTitleDo> queryBuild(Map<String, String> map) {
        QueryWrapper<InvoiceTitleDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            wrapper.and(invoiceRecordDoQueryWrapper -> invoiceRecordDoQueryWrapper.like("invoice_title", map.get("keyword"))
                    .or().like("bank", map.get("keyword")));
        }
        return wrapper;
    }

    @Override
    public List<Map> selectInvoiceListInit(Long companyId, String taxNumber) {
        List<Map> invoiceList = new ArrayList<>();
        if (companyId == null) {
            return invoiceList;
        }
        Map<String, String> param = new HashMap<>();
        param.put("companyId", companyId + "");
        param.put("taxNumber", taxNumber);
        List<InvoiceTitleOweDetailRes> oweList = this.oweList(param);
        for (InvoiceTitleOweDetailRes et : oweList) {
            Map map = new HashMap();
            map.put("id", et.getTitleId());
            map.put("titleId", et.getTitleId());
            map.put("companyId", et.getCompanyId());
            map.put("invoiceTitle", et.getInvoiceTitle());
            map.put("taxNumber", et.getTaxNumber());
            map.put("companyAddress", et.getCompanyAddress());
            map.put("oweAmount", et.getOweAmount());
            map.put("invoicing", et.isInvoicing());
            invoiceList.add(map);
        }

        return invoiceList;
    }

}
